package com.sh.tcp;

import java.net.SocketAddress;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.sh.cache.BindingCache;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.util.CharsetUtil;

/**
* @comments
* @author  zg
* @date 2018年4月6日
*/
@Sharable
public class SmartServerHandler extends ChannelInboundHandlerAdapter{
	private Logger logger = LogManager.getLogger(this.getClass());
	
	/**
	 * 当一个新的连接已经被建立时将会被调用
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	logger.info("收到客户端{}连接......", clientInfo(ctx));
		//super.channelActive(ctx);
	}
	
	
	/**
	 * 有数据可以读取的时候触发
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	ByteBuf msgBuf = (ByteBuf) msg;
    	String msgStr = msgBuf.toString(CharsetUtil.UTF_8);
    	/*byte[] msgBytes = new byte[msgBuf.readableBytes()];
    	msgBuf.readBytes(msgBytes);
    	String msgStr = new String(msgBytes,"UTF-8");*/
    	logger.info("收到客户端{}消息：{}", clientInfo(ctx), msgStr);
    	//消息格式为逗号分隔符分割的信息，形式如：sn,mac
    	//String[] params = msgStr.split(",");
    	if(StringUtils.isNotBlank(msgStr) || msgStr.indexOf(",") != -1) {
    		String[] msgArr = msgStr.split(","); 
    		if(msgArr.length < 2) {
    			logger.info("上送报文错误-内容不正确");
    		}else {
    			String bindKey = msgArr[0] + "-" + msgArr[1];
        		//把客户端发送的消息放到 BindingCache中
            	BindingCache.addDeviceInfo(bindKey);
            	//ClientChannelMap.add(bindKey, ctx.channel());
            	ClientChannelMap.add(bindKey, ctx);
    		}
    	}else {
    		logger.info("上送报文错误-格式不正确");
    	}
    	
    	/*String content = "你好！！";
    	byte[] contentBytes = content.getBytes("UTF-8");
		ByteBuf buf = ctx.alloc().buffer(); 
		buf.writeBytes(contentBytes); 
		ctx.writeAndFlush(buf);*/
		
    	//ctx.write(msgBuf);
		//super.channelRead(ctx, msg);
	}



	/**
	 * Channel从EventLoop中被取消注册，不能处理任何IO请求
	 */
	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		logger.info("客户端{}Unregistered", clientInfo(ctx));
		super.channelUnregistered(ctx);
	}

	/**
	 * channel注册到了对应的EventLoop,并且可以处理IO请求
	 */
	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		logger.info("客户端{}Registered", clientInfo(ctx));
		super.channelRegistered(ctx);
	}


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error("客户端{}exceptionCaught:", clientInfo(ctx), cause);
		super.exceptionCaught(ctx, cause);
	}

	private String clientInfo(ChannelHandlerContext ctx) {
		Channel ch = ctx.channel();
    	SocketAddress sa = ch.remoteAddress();
    	StringBuilder sbu = new StringBuilder();
    	sbu.append("(");
    	sbu.append(sa.toString());
    	sbu.append("@");
    	sbu.append(ch.hashCode());
    	sbu.append(")");
    	return sbu.toString();
	}
	
}
